<?php

namespace V1\Model;


use Think\Exception;
use Think\Model;
use V1\Model\AreaModel;

class QuestionAnswerModel extends Model
{
    protected $tableName = 'question_answer';

    /**
     * 同意数量
     * @return mixed
     */
    public function agree($userid)
    {
        $map['uid'] = !empty($userid) ? $userid : '';
        $data = D('QuestionAnswer')->where($map)->field('agree_times')->sum('agree_times');
        return $data;
    }

    /**
     * 不同意数量
     * @return mixed
     */
    public function dis_agree($userid)
    {
        $map['uid'] = !empty($userid) ? $userid : '';
        $data = D('QuestionAnswer')->where($map)->field('agree_times')->sum('against_times');
        return $data;
    }

    /**
     * 好评率
     * @param $userid
     * @return string
     */
    public function add_adoption_rates($userid)
    {
        $agree_times = $this->agree($userid);
        $against_times = $this->dis_agree($userid);
        if ($agree_times == 0 && $against_times == 0) {
            return 0;
        } else {
            $cnl = ($agree_times / ($agree_times + $against_times)) * 100;
            return round($cnl, 2) . '%';
        }
    }

    /**
     *  获取问题解答
     * @param $askid
     * @param null $start
     * @param null $limit
     * @param null $userid
     * @param int $answerid
     * @return mixed
     */
    public function get_ask_arc_answers($askid, $start = null, $limit = null, $userid = null, $answerid = 0)
    {
        $member_profile_model = new MemberProfileModel();
        $member_fans_model = new MemberFansModel();
        $question_adopt_model = new QuestionAdoptModel();
        $question_ask_model = new QuestionAskModel();
        $map['answer.askid'] = $askid;
        $data = $this->alias('answer')
            ->join('LEFT JOIN destoon_ucenter_member m_member ON answer.uid = m_member.userid')
            ->join('LEFT JOIN __MEMBER_PROFILE__ profile ON answer.uid = profile.userid')
            ->field('answer.id,answer.uid,answer.askid,answer.content,answer.addtime,answer.agree_times,answer.against_times,answer.answerid,m_member.mobile,profile.truename,profile.areaid,profile.address,profile.avatar,profile.memberships')
            ->where($map)
            ->order('addtime asc')
            ->limit($start, $limit)
            ->select();
        foreach ($data as $k => $v) {
            if (intval($v['answerid']) == 0) {
                $data[$k] = $v;
                $member = $member_profile_model->get_user_details_ask_list($v['uid']);
                if ($member['profile'][0]['is_expert'] != 0) {
                    $data[$k]['good_at_crop'] = $member['profile'][0]['expert_profile']['good_at_crop'];
                }
                $data[$k]['memberships'] = $member['profile'][0]['expert_profile']['expert_type'] != null ? $member['profile'][0]['expert_profile']['expert_type'] : $member['profile'][0]['member_profile']['memberships'];
                $data[$k]['favorable'] = $member['favorable'];    //同意率
                $data[$k]['is_ok'] = $member_fans_model->is_follow($v['uid'], $userid);    //判断是否已加关注
                $data[$k]['is_ok'] = $member_fans_model->is_follow($v['uid'], $userid);    //判断是否已加关注
                $data[$k]['reply_nickname'] = $question_ask_model->get_ask_by_uid($v['askid']);    //判断是否已加关注
                $adopt_data = $question_adopt_model->get_answer_adopt_status($askid, $v['id']);        //获取提问人的真实姓名
                if (count($adopt_data) > 0) {
                    $data[$k]['adopt'] = true;
                } else {
                    $data[$k]['adopt'] = false;
                }
            }
            //针对问题回复列表
            $AskSubQuestionData = $this->getAskSubQuestion($askid, $v['id']);
            foreach ($AskSubQuestionData AS $k2 => $v2) {
                $AskSubQuestionData[$k2]['content'] = $this->eachKeyWord($v2['content']); //获取关键词加链接
            }
            $data[$k]['question_answers_sub_list'] = $AskSubQuestionData;
        }
        return $data;
    }

    /**
     * 通过问题ID、回复ID查询是否存在子回复
     * @param $askid
     * @param $answerid
     * @return mixed
     */
    public function getAskSubQuestion($askid, $answerid)
    {
        $map['answer.askid'] = $askid;
        $map['answer.answerid'] = $answerid;
        $request = $this->alias('answer')
            ->join('LEFT JOIN __MEMBER_PROFILE__ profile ON answer.uid = profile.userid')
            ->field('answer.*,profile.truename,profile.nickname')
            ->where($map)
            ->select();
        return $request;
    }

    /**
     * 获取内容详情
     * @param $askid
     * @param $userid
     * @return mixed
     */
    public function get_problem_details($askid, $userid)
    {
        $map['id'] = $askid;
        $question_ask_model = M('question_ask');
        $integral_model = new IntegralModel();
        $member_fans_model = new MemberFansModel();
        $question_adopt_model = new QuestionAdoptModel();
        $data = $question_ask_model->alias('ask')->join('LEFT JOIN destoon_ucenter_member m_member ON ask.uid = m_member.userid')
            ->join('LEFT JOIN __MEMBER_PROFILE__ profile ON ask.uid = profile.userid')
            ->field('ask.*,m_member.mobile,profile.nickname,profile.truename,profile.areaid,profile.address,profile.avatar,profile.memberships')
            ->where($map)
            ->select();
        foreach ($data as $k => $v) {
            if (!$v['nickname']) {
                $data[$k]['nickname'] = mobileHide($v['mobile']);
            }
            $member_profile = new MemberProfileModel();
            $member = $member_profile->get_user_details_common($userid);
            $data[$k]['memberships'] = $member['profile'][0]['expert_profile']['expert_type'] != null ? $member['profile'][0]['expert_profile']['expert_type'] : $member['profile'][0]['member_profile']['memberships'];
            $data[$k]['medal'] = $member['medal'];
            //积分等级
            $data[$k]['grade_level'] = $integral_model->grade_type($member['profile'][0]['member_profile']['score'], $userid);
            //判断是否已加关注
            $data[$k]['is_ok'] = $member_fans_model->is_follow($v['uid'], $userid);
            $adopt_data = $question_adopt_model->get_answer_adopt_status($askid);                 //获取问题是否被采纳
            if (count($adopt_data) > 0) {
                $data[$k]['adopt'] = true;
            } else {
                $data[$k]['adopt'] = false;
            }
        }
        return $data;
    }

    /**
     * 获取关键词
     * @return mixed
     */
    public function getKeyWord()
    {
        $list = M('keyword')->field('keyword')->select();
        return $list;
    }

    /**
     * 遍历循环关键词
     * @param $content
     * @return mixed
     */
    public function eachKeyWord($content)
    {
        $key = $this->getKeyWord();
        foreach ($key AS $k => $v) {
            $content = str_replace($v["keyword"], "<a href='http://www.nongyao001.com/sell/search.php?uagent=touch&searchid=5&kw=" . urlencode(iconv('utf-8', 'gb2312', $v["keyword"])) . "' style='color:red'>" . $v["keyword"] . "</a>", $content);
        }
        return $content;
    }

    /**
     * 回答问题
     * @param $info
     * @return false|int
     */
    public function addQuestionAnswer($info)
    {
        //判断是否重复提交
        $qa_status = $this->getQuestionAnswerStatus($info);
        if ($qa_status == false) {
            return 0;
            exit;
        }
        if (empty($info['reply_nickname']) || $info['reply_nickname'] == null) {
            $reply_nickname = 0;
        } else {
            $reply_nickname = $info['reply_nickname'];
        }
        $answerid = $info['answerid'] != '' ? $info['answerid'] : 0; //判断是否存在问题ID 不存在默认值为0
        $request = [
            'uid' => $info['uid'],
            'reply_nickname' => $reply_nickname,
            'askid' => $info['askid'],
            'content' => urldecode($info['content']),
            'addtime' => time(),
            'answerid' => $answerid
        ];
        return $this->add($request);
    }

    /**
     * 获取回答问题数量
     * @param $askid [问题id]
     * @return mixed
     */
    public function get_answer_number($askid = '')
    {
        $request = $this->where(array('askid' => $askid))->count();
        return $request;
    }

    /**
     * 获取历史回答列表
     * @param $u_id
     * @return array
     */
    public function get_uid_by_answer_list($u_id)
    {
        $question_ask_model = new QuestionAskModel();
        $data = $this
            ->field('askid')
            ->where(array('uid' => $u_id))
            ->order('addtime desc')
            ->select();
        if ($data === false) {
            new Exception();
        } else {
            foreach ($data as $k => $v) {
                $askid[] = $v['askid'];
            }
            $askid = array_unique($askid);
            foreach ($askid as $k => $v) {
                $data = $question_ask_model->get_id_by_ask_list($v);
                if (!empty($data)) {
                    $list[] = $data;
                }
            }
            return $list;
        }
    }

    /**
     * 点赞设置
     * @param $u_id
     * @param $status
     * @param $from_uid
     * @param $answer_id
     * @return int
     */
    public function set_agree($u_id, $status, $from_uid, $answer_id)
    {
        $data['uid'] = $u_id;
        $data['id'] = $answer_id;
        if ($status == 1) {
            $result = $this->where($data)->setInc('agree_times', 1);
        } else {
            $result = $this->where($data)->setInc('against_times', 1);
        }
        $agree_times = $this->where($data)->field('agree_times')->find();
        $against_times = $this->where($data)->field('against_times')->find();
        $message_model = new MessageModel();
        $message_model->add_message_agree($from_uid, $u_id, $answer_id);
        if ($result) {
            $show['agree_times'] = $agree_times['agree_times'];
            $show['against_times'] = $against_times['against_times'];
            return $show;
        } else {
            return false;
        }
    }

    /**
     * 判断是否重复回复问答（默认8秒）
     * @param $info
     * @return bool
     */
    private function getQuestionAnswerStatus($info)
    {
        $map['uid'] = $info['userid'];
        $map['askid'] = $info['askid'];
        $request = $this->field('addtime')->where($map)->order('addtime desc')->find();
        if (!empty($request['addtime'])) {
            if ((time() - $request['addtime']) < 8) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }


}